<template>
  <div class="login flex-c-c">
    <div class="login-box">
      <div class="logo-box">
        <i class="logo"></i>
        <div class="title-main">AIGC AI绘画</div>
        <div class="title-sub">欢迎登录AIGC AI绘画</div>
      </div>
      <div class="form-box">
        <ElForm ref="form" :model="formLogin" :rules="formRules" size="large">
          <ElFormItem prop="username">
            <ElInput placeholder="请输入手机号" v-model="formLogin.username">
              <template #prefix>
                <ElIcon color="var(--el-color-primary)"><User /></ElIcon>
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="password">
            <ElInput placeholder="请输入密码" type="password" v-model="formLogin.password">
              <template #prefix>
                <ElIcon color="var(--el-color-primary)"><Lock /></ElIcon>
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="picCode">
            <ElInput placeholder="请输入验证码" :maxlength="4" v-model="formLogin.picCode" @keyup.enter="doLogin">
              <template #prefix>
                <ElIcon color="var(--el-color-primary)"><Edit /></ElIcon>
              </template>
              <template #append>
                <img class="verify-code" :src="imgVerifyCode" alt="验证码" @click="getVerifyCode" />
              </template>
            </ElInput>
          </ElFormItem>
          <ElFormItem>
            <!-- <ElCheckbox v-model="isRemember">记住我</ElCheckbox> -->
          </ElFormItem>
        </ElForm>
      </div>
      <div class="btn-box">
        <ElButton class="btn-login" type="primary" :loading="isLoading" @click="doLogin">登录</ElButton>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import AuthService from '@/api/service/AuthService'
import FuncCrypt from '@/utils/FuncCrypt'
import useGlobalStore from '@/store/modules/global'
import router from '@/router'
import { ElMessage } from 'element-plus'

// 全局缓存
const globalStore = useGlobalStore()
// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[23456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  picCode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}
// 是否记住密码
const isRemember = ref(false)
// 是否载入中
const isLoading = ref(false)
// 表单DOM
const form = ref()
// 表单数据
const formLogin = ref({} as ApiAuth.ReqLogin)
// 验证码图片链接
const imgVerifyCode = ref('')
// 公钥
const pubKey = ref('')
// 初始化
const init = () => {
  getVerifyCode()
  getPubKey()
}

// 获取验证码
const getVerifyCode = async () => {
  const result = await AuthService.getVerifyCode<ApiAuth.VerifyCodeRes>()

  if (result && result.code === globalStore.res_success) {
    let data = result.result
    imgVerifyCode.value = data.image
    formLogin.value.picToken = data.token
  }
}
// 获取公钥
const getPubKey = () => {
  AuthService.getPubKey().then((res: any) => {
    pubKey.value = res.result
  })
}
// 登录
const setLogin = async () => {
  let params = Object.assign(
    {
      lt: 'ncc'
    },
    formLogin.value
  ) as any
  params.username = FuncCrypt.rsaEncrypt(formLogin.value.username, pubKey.value)
  params.password = FuncCrypt.rsaEncrypt(formLogin.value.password, pubKey.value)
  isLoading.value = true
  const result = await AuthService.setLogin(params)
  isLoading.value = false
  if (result.code === globalStore.$state.res_success) {
    let data: any = result.result
    globalStore.setUserInfo(data.user.detail)
    globalStore.setToken(`${data.tokenType} ${data.value}`)
    globalStore.setPermissions(data.user.permissions)
    if (isRemember.value) {
      // 如果记住密码
      globalStore.setPassword(params.password)
      globalStore.setUsername(params.username)
    }
    ElMessage({
      message: '登录成功',
      type: 'success'
    })
    nextTick(() => {
      router.push('/')
    })
  } else {
    ElMessage.error(result.msg)
    getVerifyCode()
  }
}

// 点击登录
const doLogin = () => {
  // 检查表单规则是否通过
  form.value.validate((isPass: Boolean) => {
    if (isPass) {
      setLogin()
    }
  })
}

onMounted(() => {
  init()
})
</script>
<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background: url('@image/login/img_BG.jpg') no-repeat center / 100% 100%;

  .login-box {
    width: 773px;
    height: 535px;
    padding: 50px 150px;
    background: url('@image/login/login_box.png') no-repeat center / 100% 100%;

    .logo-box {
      text-align: center;
      margin-bottom: 15px;

      .logo {
        display: block;
        width: 103px;
        height: 30px;
        margin: auto;
        background: url('@image/logo/logo_full.png') no-repeat center / contain;
      }
      .title-main {
        font: 30px/60px 'AlibabaPuHuiTiB';
        letter-spacing: 3px;
      }
      .title-sub {
        font: 18px/18px AlibabaPuHuiTi-Regular;
        letter-spacing: 1px;

        &::before {
          content: '—';
          margin-right: 15px;
        }
        &::after {
          content: '—';
          margin-left: 15px;
        }
      }
    }
  }
  .form-box {
    .verify-code {
      height: 36px;
      cursor: pointer;
    }
    :deep(.el-form-item) {
      margin-bottom: 15px;
      .el-input {
        margin-top: 15px;

        .el-input-group__append {
          padding: 0 2px;
        }
      }
    }
  }
  .btn-box {
    .btn-login {
      display: block;
      width: 213px;
      height: 45px;
      margin: auto;
    }
  }
}
</style>
